import React, { useState, useEffect } from "react";
import {
  Card,
  List,
  Space,
  Button,
  Tag,
  Input,
  Select,
  Modal,
  message,
  Form,
  Typography,
  Avatar,
  Tooltip,
  Empty,
  Spin,
  Tabs,
  Badge,
} from "antd";
import {
  MessageOutlined,
  LikeOutlined,
  LikeFilled,
  EyeOutlined,
  UserOutlined,
  RobotOutlined,
  PushpinOutlined,
  SendOutlined,
  CommentOutlined,
} from "@ant-design/icons";
import styled from "styled-components";
import type {
  DiscussionPost,
  DiscussionFilter,
  DiscussionReply,
} from "../../common/types/discussion";
import { useUser } from "../../../contexts/UserContext";
import discussionService from "../../../services/discussion";
import NewDiscussion from "./components/NewDiscussion";
import DiscussionDetail from "./components/DiscussionDetail";
import MyDiscussions from "./components/MyDiscussions";

const { Search } = Input;
const { Title, Text, Paragraph } = Typography;
const { TextArea } = Input;

// 根据用户角色生成默认头像
const getDefaultAvatar = (name: string, role: string) => {
  // 使用姓名的hash值作为种子，避免中文编码问题
  const hash = name.split('').reduce((a, b) => {
    a = ((a << 5) - a) + b.charCodeAt(0);
    return a & a;
  }, 0);
  const seed = Math.abs(hash).toString();
  
  // 根据角色设置不同的卡通头像样式
  if (role === "teacher") {
    // 教师使用更成熟的卡通风格
    return `https://api.dicebear.com/7.x/adventurer/svg?seed=${seed}&backgroundColor=b6e3f4`;
  } else {
    // 学生使用活泼的卡通风格
    return `https://api.dicebear.com/7.x/personas/svg?seed=${seed}&backgroundColor=ffdfbf`;
  }
};

const StyledCard = styled(Card)`
  margin-bottom: 24px;
  .ant-card-head-title {
    font-weight: bold;
  }
`;

const ReplyForm = styled(Form)`
  margin-top: 16px;
  .ant-form-item:last-child {
    margin-bottom: 0;
  }
`;

const DiscussionItem = styled.div`
  padding: 24px 0;
  border-bottom: 1px solid #f0f0f0;
  margin-bottom: 16px;
  
  &:last-child {
    border-bottom: none;
  }
`;

const StudentDiscussion: React.FC = () => {
  const { user } = useUser();
  const [loading, setLoading] = useState(false);
  const [discussions, setDiscussions] = useState<DiscussionPost[]>([]);
  const [filter, setFilter] = useState<DiscussionFilter>({
    sortBy: "latest",
  });
  const [isNewDiscussionVisible, setIsNewDiscussionVisible] = useState(false);
  const [selectedDiscussion, setSelectedDiscussion] = useState<string>();
  const [replyForm] = Form.useForm();
  const [likedDiscussions, setLikedDiscussions] = useState<Set<string>>(new Set());
  const [expandedReplies, setExpandedReplies] = useState<Set<string>>(new Set());

  useEffect(() => {
    loadDiscussions();
  }, [filter]);

  const loadDiscussions = async () => {
    setLoading(true);
    try {
      // 生成更丰富的mock数据，确保AI回复状态正确对应
      const generateMockDiscussions = (): DiscussionPost[] => {
        const topics = [
          "数据结构中链表和数组的区别是什么？",
          "数据库设计中的范式化问题",
          "计算机网络TCP三次握手详解",
          "操作系统进程调度算法比较",
          "软件工程中敏捷开发的优势",
          "机器学习算法选择指南",
          "前端框架React vs Vue对比",
          "后端API设计最佳实践",
          "云计算服务模式IaaS、PaaS、SaaS",
          "大数据处理技术栈介绍",
          "人工智能在医疗领域的应用",
          "区块链技术原理与应用",
          "网络安全防护策略",
          "移动应用开发趋势",
          "DevOps实践与工具链"
        ];

        const contents = [
          "有没有开源项目可以参考学习？",
          "在实际项目中如何平衡范式化和性能？",
          "为什么需要三次握手而不是两次？",
          "不同调度算法适用于什么场景？",
          "如何在小团队中实施敏捷开发？",
          "如何根据数据特征选择合适的算法？",
          "两个框架各自的优缺点是什么？",
          "如何设计RESTful API？",
          "企业如何选择合适的云服务？",
          "Hadoop生态系统的组件有哪些？",
          "AI在诊断方面有哪些突破？",
          "区块链如何保证数据不可篡改？",
          "如何防范常见的网络攻击？",
          "跨平台开发框架有哪些选择？",
          "如何实现持续集成和部署？"
        ];

        const tags = [
          ["数据结构", "算法", "链表"],
          ["数据库", "设计模式", "性能优化"],
          ["网络协议", "TCP", "通信"],
          ["操作系统", "进程管理", "调度"],
          ["软件工程", "敏捷开发", "项目管理"],
          ["机器学习", "算法", "数据科学"],
          ["前端开发", "React", "Vue"],
          ["后端开发", "API设计", "架构"],
          ["云计算", "服务模式", "部署"],
          ["大数据", "Hadoop", "分布式"],
          ["人工智能", "医疗", "应用"],
          ["区块链", "分布式", "安全"],
          ["网络安全", "防护", "攻击"],
          ["移动开发", "跨平台", "趋势"],
          ["DevOps", "CI/CD", "自动化"]
        ];

        const authors = [
          { name: "杨梦瑶", role: "student" as const },
          { name: "张伟", role: "student" as const },
          { name: "李娜", role: "student" as const },
          { name: "王强", role: "student" as const },
          { name: "陈静", role: "student" as const },
          { name: "刘洋", role: "student" as const },
          { name: "赵敏", role: "student" as const },
          { name: "孙浩", role: "student" as const },
          { name: "周婷", role: "student" as const },
          { name: "吴磊", role: "student" as const },
          { name: "郑华", role: "student" as const },
          { name: "冯雪", role: "student" as const },
          { name: "朱明", role: "student" as const },
          { name: "秦芳", role: "student" as const },
          { name: "许杰", role: "student" as const }
        ];

        return Array.from({ length: 15 }, (_, index) => {
          const author = authors[index % authors.length];
          const hasAIResponse = index % 3 === 0; // 每3个讨论中有1个有AI回复
          const replyCount = Math.floor(Math.random() * 8) + 1; // 1-8条回复
          
          // 生成回复
          const replies: DiscussionReply[] = Array.from({ length: replyCount }, (_, replyIndex) => ({
            id: `${index}-${replyIndex}`,
            content: [
              "这个问题很有意思，我也遇到过类似的情况。",
              "感谢分享，这个思路很有启发性。",
              "我觉得可以从另一个角度来思考这个问题。",
              "这个解决方案确实很实用，学到了！",
              "有没有更详细的参考资料推荐？",
              "这个观点我同意，但还需要考虑其他因素。",
              "谢谢解答，让我对这个问题有了新的认识。",
              "这个例子很生动，容易理解。"
            ][replyIndex % 8],
            author: {
              id: `user-${replyIndex}`,
              name: ["张三", "李四", "王五", "赵六", "钱七", "孙八", "周九", "吴十"][replyIndex % 8],
              role: "student" as const,
              avatar: getDefaultAvatar(["张三", "李四", "王五", "赵六", "钱七", "孙八", "周九", "吴十"][replyIndex % 8], "student")
            },
            createTime: new Date(Date.now() - Math.random() * 7 * 24 * 60 * 60 * 1000).toLocaleString('zh-CN'),
            likes: Math.floor(Math.random() * 10)
          }));

          return {
            id: `discussion-${index + 1}`,
            title: topics[index],
            content: contents[index],
            author: {
              id: `author-${index}`,
              name: author.name,
              role: author.role,
              avatar: getDefaultAvatar(author.name, author.role)
            },
            createTime: new Date(Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000).toLocaleString('zh-CN'),
            tags: tags[index],
            views: Math.floor(Math.random() * 1000) + 100,
            likes: Math.floor(Math.random() * 50) + 5,
            replies,
            aiResponse: hasAIResponse ? {
              content: `这是一个很好的问题！让我为您详细解答：

${topics[index]}涉及到${tags[index][0]}领域的核心概念。在实际应用中，我们需要考虑以下几个方面：

1. **理论基础**：理解${tags[index][0]}的基本原理和特点
2. **实践应用**：在实际项目中如何正确使用
3. **性能优化**：如何提高效率和性能
4. **最佳实践**：行业内的标准做法和推荐方案

建议您可以：
- 查阅相关技术文档
- 参考开源项目源码
- 参与技术社区讨论
- 动手实践验证理论

希望这个回答对您有帮助！如果还有疑问，欢迎继续讨论。`,
              createTime: new Date(Date.now() - Math.random() * 24 * 60 * 60 * 1000).toLocaleString('zh-CN'),
              status: "completed" as const
            } : undefined,
            aiRequestStatus: hasAIResponse ? "completed" as const : "pending" as const
          };
        });
      };

      const mockDiscussions = generateMockDiscussions();
      
      // 根据筛选条件排序
      let sortedDiscussions = [...mockDiscussions];
      switch (filter.sortBy) {
        case "latest":
          sortedDiscussions.sort((a, b) => new Date(b.createTime).getTime() - new Date(a.createTime).getTime());
          break;
        case "popular":
          sortedDiscussions.sort((a, b) => b.likes - a.likes);
          break;
        case "mostReplies":
          sortedDiscussions.sort((a, b) => b.replies.length - a.replies.length);
          break;
      }

      setDiscussions(sortedDiscussions);
    } catch (error) {
      console.error("加载讨论失败:", error);
      message.error("加载讨论失败");
    } finally {
      setLoading(false);
    }
  };

  const handleSearch = (value: string) => {
    setFilter(prev => ({ ...prev, keyword: value }));
  };

  const handleSortChange = (value: "latest" | "popular" | "mostReplies") => {
    setFilter(prev => ({ ...prev, sortBy: value }));
  };

  const handleTagClick = (tag: string) => {
    setFilter(prev => ({ 
      ...prev, 
      tags: prev.tags?.includes(tag) 
        ? prev.tags.filter(t => t !== tag)
        : [...(prev.tags || []), tag]
    }));
  };

  const handleNewDiscussion = () => {
    setIsNewDiscussionVisible(true);
  };

  const handleNewDiscussionSubmit = async (values: {
    title: string;
    content: string;
    tags: string[];
    requestAIResponse: boolean;
  }) => {
    if (!user) {
      message.warning("请先登录");
      return;
    }

    try {
      const newDiscussion: DiscussionPost = {
        id: `discussion-${Date.now()}`,
        title: values.title,
        content: values.content,
        author: {
          id: String(user.id),
          name: user.name,
          role: user.role,
          avatar: getDefaultAvatar(user.name, user.role)
        },
        createTime: new Date().toLocaleString('zh-CN'),
        tags: values.tags,
        views: 0,
        likes: 0,
        replies: [],
        aiRequestStatus: values.requestAIResponse ? "pending" as const : undefined
      };

      // 如果申请AI回复，模拟AI回复生成
      if (values.requestAIResponse) {
        message.loading("AI正在分析您的问题...", 2);
        
        // 模拟AI回复生成延迟
        setTimeout(() => {
          const aiResponse = {
            content: `感谢您的提问！关于"${values.title}"，我来为您详细解答：

${values.content}

基于您的问题，我建议从以下几个方面来思考：

1. **问题分析**：理解问题的核心和关键点
2. **解决方案**：提供具体的解决思路和方法
3. **实践建议**：给出实用的操作建议
4. **学习资源**：推荐相关的学习资料

希望这个回答对您有帮助！如果还有其他问题，欢迎继续讨论。`,
            createTime: new Date().toLocaleString('zh-CN'),
            status: "completed" as const
          };

          setDiscussions(prev => prev.map(d => 
            d.id === newDiscussion.id 
              ? { ...d, aiResponse, aiRequestStatus: "completed" as const }
              : d
          ));

          message.success("AI回复已生成！");
        }, 3000);
      }

      setDiscussions(prev => [newDiscussion, ...prev]);
      setIsNewDiscussionVisible(false);
      message.success("讨论发布成功！");
    } catch (error) {
      console.error("发布讨论失败:", error);
      message.error("发布讨论失败，请重试");
    }
  };

  const handleLike = async (discussionId: string) => {
    if (!user) {
      message.warning("请先登录");
      return;
    }

    try {
      const isLiked = likedDiscussions.has(discussionId);
      const newLikedDiscussions = new Set(likedDiscussions);
      
      if (isLiked) {
        newLikedDiscussions.delete(discussionId);
      } else {
        newLikedDiscussions.add(discussionId);
      }
      
      setLikedDiscussions(newLikedDiscussions);
      
      setDiscussions(prev => prev.map(d => 
        d.id === discussionId 
          ? { ...d, likes: isLiked ? d.likes - 1 : d.likes + 1 }
          : d
      ));

      message.success(isLiked ? "取消点赞" : "点赞成功");
    } catch (error) {
      console.error("点赞失败:", error);
      message.error("操作失败，请重试");
    }
  };

  const handleView = (discussionId: string) => {
    setDiscussions(prev => prev.map(d => 
      d.id === discussionId 
        ? { ...d, views: d.views + 1 }
        : d
    ));
  };

  const handleViewReplies = (discussionId: string) => {
    const newExpandedReplies = new Set(expandedReplies);
    if (newExpandedReplies.has(discussionId)) {
      newExpandedReplies.delete(discussionId);
    } else {
      newExpandedReplies.add(discussionId);
    }
    setExpandedReplies(newExpandedReplies);
  };

  const handleReply = async (discussionId: string) => {
    if (!user) {
      message.warning("请先登录");
      return;
    }

    try {
      const values = await replyForm.validateFields();
      const newReply: DiscussionReply = {
        id: Date.now().toString(),
        content: values.content,
        author: {
          id: String(user.id),
          name: user.name,
          role: user.role,
          avatar: getDefaultAvatar(user.name, user.role)
        },
        createTime: new Date().toLocaleString('zh-CN'),
        likes: 0
      };

      setDiscussions(prev => prev.map(d => 
        d.id === discussionId 
          ? { ...d, replies: [...d.replies, newReply] }
          : d
      ));

      replyForm.resetFields();
      message.success("回复成功！");
    } catch (error) {
      if (error instanceof Error) {
        message.error("回复失败，请重试");
        console.error("回复失败:", error);
      }
    }
  };

  const handleRequestAIResponse = async (discussionId: string) => {
    try {
      message.loading("正在申请AI回复...", 2);
      
      // 模拟AI回复生成
      setTimeout(() => {
        const discussion = discussions.find(d => d.id === discussionId);
        if (discussion) {
          const aiResponse = {
            content: `关于"${discussion.title}"，AI为您提供以下专业解答：

${discussion.content}

基于您的问题，我建议：

1. **深入理解**：掌握相关概念的核心要点
2. **实践应用**：在实际项目中验证理论
3. **持续学习**：关注技术发展趋势
4. **交流分享**：与同行交流学习心得

希望这个回答对您有帮助！`,
            createTime: new Date().toLocaleString('zh-CN'),
            status: "completed" as const
          };

          setDiscussions(prev => prev.map(d => 
            d.id === discussionId 
              ? { ...d, aiResponse, aiRequestStatus: "completed" as const }
              : d
          ));

          message.success("AI回复已生成！");
        }
      }, 3000);
    } catch (error) {
      console.error("申请AI回复失败:", error);
      message.error("申请失败，请重试");
    }
  };

  const renderAllDiscussions = () => (
      <StyledCard
        title={
          <Space>
            <Title level={4} style={{ margin: 0 }}>
              课程讨论区
            </Title>
          </Space>
        }
        extra={
          <Space>
            <Search
              placeholder="搜索讨论..."
              onSearch={handleSearch}
              style={{ width: 300 }}
            />
            <Select
              value={filter.sortBy}
              onChange={handleSortChange}
              style={{ width: 120 }}
              options={[
                { label: "最新", value: "latest" },
                { label: "最热", value: "popular" },
                { label: "最多回复", value: "mostReplies" },
              ]}
            />
            <Button type="primary" onClick={handleNewDiscussion}>
              发起讨论
            </Button>
          </Space>
        }
      >
        {loading ? (
          <div style={{ textAlign: "center", padding: "40px 0" }}>
            <Spin />
          </div>
        ) : discussions.length === 0 ? (
          <Empty description="暂无讨论" />
        ) : (
          <List<DiscussionPost>
            itemLayout="vertical"
            dataSource={discussions}
            renderItem={(item) => (
              <DiscussionItem>
                <div style={{ width: "100%" }}>
                  {/* 讨论头部信息 */}
                  <div style={{ display: "flex", alignItems: "flex-start", marginBottom: "16px" }}>
                    <Avatar 
                      src={item.author.avatar}
                      icon={<UserOutlined />} 
                      style={{ marginRight: "12px", marginTop: "4px" }}
                    />
                    <div style={{ flex: 1 }}>
                      <div style={{ display: "flex", alignItems: "center", marginBottom: "8px" }}>
                        <Space>
                          {item.isPinned && (
                            <Tooltip title="已置顶">
                              <PushpinOutlined style={{ color: "#1890ff" }} />
                            </Tooltip>
                          )}
                          <a
                            href="#"
                            onClick={(e) => {
                              e.preventDefault();
                              setSelectedDiscussion(item.id);
                            }}
                            style={{ 
                              fontSize: "16px", 
                              fontWeight: 600, 
                              color: "#1890ff",
                              textDecoration: "none"
                            }}
                          >
                            {item.title}
                          </a>
                          {item.aiResponse && (
                            <Tag icon={<RobotOutlined />} color="purple">
                              AI已回复
                            </Tag>
                          )}
                        </Space>
                      </div>
                      <div style={{ display: "flex", alignItems: "center", marginBottom: "12px" }}>
                        <Space>
                          <Text strong>{item.author.name}</Text>
                          <Tag
                            color={
                                item.author.role === "teacher" ? "blue" : "default"
                            }
                          >
                            {item.author.role === "teacher" ? "教师" : "学生"}
                          </Tag>
                          <Text type="secondary">发布于 {item.createTime}</Text>
                        </Space>
                      </div>
                      <div style={{ marginBottom: "12px" }}>
                        {item.tags.map((tag) => (
                          <Tag
                            key={tag}
                            color={
                              filter.tags?.includes(tag) ? "blue" : "default"
                            }
                            style={{ cursor: "pointer", marginRight: "8px" }}
                            onClick={() => handleTagClick(tag)}
                          >
                            {tag}
                          </Tag>
                        ))}
                      </div>
                    </div>
                  </div>

                  {/* 讨论内容 */}
                  <div style={{ marginBottom: "16px", paddingLeft: "44px" }}>
                    <Paragraph
                      ellipsis={{ rows: 2, expandable: true, symbol: "展开" }}
                      style={{ margin: 0, fontSize: "14px", lineHeight: "1.6" }}
                    >
                      {item.content}
                    </Paragraph>
                  </div>

                  {/* 操作按钮区域 */}
                  <div style={{ 
                    display: "flex", 
                    justifyContent: "space-between", 
                    alignItems: "center",
                    paddingLeft: "44px",
                    paddingTop: "12px",
                    borderTop: "1px solid #f5f5f5"
                  }}>
                    <Space size="large">
                      <Tooltip title="点击增加浏览量">
                        <Button
                          type="text"
                          icon={<EyeOutlined />}
                          onClick={() => handleView(item.id)}
                          style={{ color: "#666" }}
                        >
                          {item.views}
                        </Button>
                      </Tooltip>
                      <Tooltip title={
                        user 
                          ? (likedDiscussions.has(item.id) ? "取消点赞" : "点赞")
                          : "登录后即可点赞"
                      }>
                        <Button
                          type="text"
                          icon={likedDiscussions.has(item.id) ? <LikeFilled /> : <LikeOutlined />}
                          onClick={() => handleLike(item.id)}
                          disabled={!user}
                          style={{ 
                            color: likedDiscussions.has(item.id) ? "#ff4d4f" : "#666"
                          }}
                        >
                          {item.likes}
                        </Button>
                      </Tooltip>
                      <Tooltip title="查看回复">
                        <Button
                          type="text"
                          icon={<MessageOutlined />}
                          onClick={() => handleViewReplies(item.id)}
                          style={{ color: "#666" }}
                        >
                          {item.replies.length}
                        </Button>
                      </Tooltip>
                      {item.aiRequestStatus === "pending" && (
                        <Tooltip title="申请AI回复">
                          <Button
                            type="text"
                            icon={<CommentOutlined />}
                            onClick={() => handleRequestAIResponse(item.id)}
                            style={{ color: "#666" }}
                          >
                            申请AI
                          </Button>
                        </Tooltip>
                      )}
                    </Space>
                  </div>

                  {/* 回复表单 */}
                  {user && (
                    <div style={{ 
                      marginTop: "16px", 
                      paddingLeft: "44px",
                      padding: "16px",
                      backgroundColor: "#fafafa",
                      borderRadius: "8px"
                    }}>
                    <ReplyForm form={replyForm}>
                      <Form.Item
                        name="content"
                        rules={[{ required: true, message: "请输入回复内容" }]}
                        style={{ marginBottom: "24px" }}
                      >
                        <TextArea
                          placeholder="写下你的回复..."
                          autoSize={{ minRows: 2, maxRows: 6 }}
                          maxLength={500}
                          showCount
                          style={{ borderRadius: "6px" }}
                        />
                      </Form.Item>
                      <Form.Item style={{ marginBottom: 0 }}>
                        <div style={{ 
                          display: "flex", 
                          justifyContent: "space-between", 
                          alignItems: "center" 
                        }}>
                          <div style={{ flex: 1 }}></div>
                          <Button
                            type="primary"
                            icon={<SendOutlined />}
                            onClick={() => handleReply(item.id)}
                            style={{ borderRadius: "6px" }}
                          >
                            发表回复
                          </Button>
                        </div>
                      </Form.Item>
                    </ReplyForm>
                    </div>
                  )}

                  {/* AI回复显示 */}
                  {item.aiResponse && (
                    <div style={{ 
                      marginTop: "16px", 
                      paddingLeft: "44px",
                      padding: "16px",
                      backgroundColor: "#f0f8ff",
                      borderRadius: "8px",
                      border: "1px solid #d6e4ff"
                    }}>
                      <div style={{ display: "flex", alignItems: "center", marginBottom: "12px" }}>
                        <RobotOutlined style={{ color: "#1890ff", marginRight: "8px" }} />
                        <Text strong style={{ color: "#1890ff" }}>AI回复</Text>
                        <Text type="secondary" style={{ marginLeft: "8px", fontSize: "12px" }}>
                          {item.aiResponse.createTime}
                        </Text>
                      </div>
                      <Paragraph style={{ margin: 0, fontSize: "14px", lineHeight: "1.6" }}>
                        {item.aiResponse.content}
                      </Paragraph>
                    </div>
                  )}

                  {/* 回复列表 */}
                  {expandedReplies.has(item.id) && (
                    <div style={{ 
                      marginTop: "16px", 
                      paddingLeft: "44px"
                    }}>
                      <div style={{ 
                        padding: "16px",
                        backgroundColor: "#fafafa",
                        borderRadius: "8px"
                      }}>
                        <div style={{ marginBottom: "16px" }}>
                          <Text strong>回复 ({item.replies.length})</Text>
                        </div>
                        
                        {item.replies.length > 0 ? (
                          <List
                            dataSource={item.replies}
                            renderItem={(reply) => (
                              <div style={{ 
                                padding: "12px 0",
                                borderBottom: "1px solid #f0f0f0"
                              }}>
                                <div style={{ display: "flex", alignItems: "flex-start" }}>
                                  <Avatar 
                                    src={reply.author.avatar}
                                    icon={<UserOutlined />} 
                                    size="small"
                                    style={{ marginRight: "8px", marginTop: "2px" }}
                                  />
                                  <div style={{ flex: 1 }}>
                                    <div style={{ display: "flex", alignItems: "center", marginBottom: "4px" }}>
                                      <Text strong style={{ fontSize: "13px" }}>
                                        {reply.author.name}
                                      </Text>
                                      <Tag
                                        color={reply.author.role === "teacher" ? "blue" : "default"}
                                        style={{ marginLeft: "8px", fontSize: "12px" }}
                                      >
                                        {reply.author.role === "teacher" ? "教师" : "学生"}
                                      </Tag>
                                      <Text type="secondary" style={{ marginLeft: "8px", fontSize: "12px" }}>
                                        {reply.createTime}
                                      </Text>
                                    </div>
                                    <Paragraph style={{ margin: 0, fontSize: "13px", lineHeight: "1.5" }}>
                                      {reply.content}
                                    </Paragraph>
                                  </div>
                                </div>
                              </div>
                            )}
                          />
                        ) : (
                          <div style={{ textAlign: "center", padding: "20px", color: "#999" }}>
                            暂无回复
                          </div>
                        )}
                      </div>
                    </div>
                  )}
                </div>
              </DiscussionItem>
            )}
            pagination={{
              pageSize: 10,
              showSizeChanger: true,
              showQuickJumper: true,
              showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
            }}
          />
        )}
      </StyledCard>
  );

  return (
    <div style={{ padding: "24px" }}>
      <Tabs
        defaultActiveKey="all"
        items={[
          {
            key: "all",
            label: "全部讨论",
            children: renderAllDiscussions()
          },
          {
            key: "my",
            label: "我的讨论",
            children: <MyDiscussions />
          }
        ]}
      />

      <NewDiscussion
        visible={isNewDiscussionVisible}
        onCancel={() => setIsNewDiscussionVisible(false)}
        onSubmit={handleNewDiscussionSubmit}
      />

      {selectedDiscussion && (
        <DiscussionDetail
          discussionId={selectedDiscussion}
          onClose={() => setSelectedDiscussion(undefined)}
          likedDiscussions={likedDiscussions}
          onLikeChange={(discussionId, isLiked) => {
            const newLikedDiscussions = new Set(likedDiscussions);
            if (isLiked) {
              newLikedDiscussions.add(discussionId);
            } else {
              newLikedDiscussions.delete(discussionId);
            }
            setLikedDiscussions(newLikedDiscussions);
          }}
        />
      )}
    </div>
  );
};

export default StudentDiscussion;
